import 'package:flutter/material.dart';
import 'dart:async';
import 'package:ichinesereader/controller/bindings.dart';
import 'package:ichinesereader/localization/localization.dart';
import 'package:ichinesereader/pages/login/loginReactive.dart';
import 'package:ichinesereader/themes/appTheme.dart';
import 'package:flutter/gestures.dart';
import 'package:ichinesereader/routes/routes.dart';
import 'package:url_strategy/url_strategy.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:get/get.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

void main() async {
  // to catch exceptions and prevent app crash
  runZonedGuarded(() async {
    WidgetsFlutterBinding.ensureInitialized();
    await Hive.initFlutter();
    await Hive.openBox('appconfig');

    LazyBinding().dependencies();
    //https://stackoverflow.com/questions/44250184/setting-environment-variables-in-flutter
    const bool isProduction = bool.fromEnvironment('dart.vm.product');

    FlutterError.onError = (FlutterErrorDetails errorDetails) {
      Log.debug("${errorDetails.exception.toString()}");
    };

    ////////编译web版本把这个权限申请去掉，会引起blank page
    try {
      //判断系统android, ios app后申请摄像头和麦克风的权限
      // 加载文件下载的初始化也得去掉web版本
      if (!GetPlatform.isWeb && !GetPlatform.isDesktop) {
        if (GetPlatform.isAndroid) {
          await InAppWebViewController.setWebContentsDebuggingEnabled(true);
        }
        if (GetPlatform.isIOS || GetPlatform.isAndroid) {
          await Permission.camera.request();
          await Permission.microphone.request();
        }
      }
    } catch (error) {}

    await dotenv.load(fileName: isProduction ? 'pro.env' : 'mig.env');
    setPathUrlStrategy();
    configLoading();
    runApp(MyApp());
  }, (error, stackTrace) {
    Log.debug("Others catching ${error.toString()}");
  });
}

void configLoading() {
  EasyLoading.instance
    ..displayDuration = const Duration(milliseconds: 3000)
    ..indicatorType = EasyLoadingIndicatorType.fadingCircle
    ..loadingStyle = EasyLoadingStyle.custom
    ..indicatorSize = 150.0
    ..radius = 6.0
    ..progressColor = Colors.transparent
    ..indicatorColor = Get.theme.primaryColorDark
    ..textColor = Colors.transparent
    ..backgroundColor = Colors.transparent
    ..dismissOnTap = true
    ..boxShadow = <BoxShadow>[];
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  static final navigatorKey = GlobalKey<NavigatorState>();

  @override
  Widget build(BuildContext context) {
    final box = Hive.box('appconfig');
    int locale = box.get('locale', defaultValue: 0);
    bool isDark = box.get('theme', defaultValue: 0) == 1;
    // can't get seeting yet in main so get Expected a value of type 'bool', but got one of type 'Null'
    // var profile =
    //     json.decode(box.get(CacheManagerKey['profilesettings'].toString()));
    // bool interfaceChinese = profile["interfaceChinese"];

    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      //scrollBehavior: MyCustomScrollBehavior(),
      scrollBehavior: MaterialScrollBehavior().copyWith(
        dragDevices: {
          PointerDeviceKind.mouse,
          PointerDeviceKind.touch,
          PointerDeviceKind.stylus,
          PointerDeviceKind.unknown
        },
      ),
      smartManagement: SmartManagement.full,
      navigatorKey: navigatorKey,
      title: "iChineseReader",
      theme: AppTheme.lightTheme,
      darkTheme: AppTheme.dartTheme,
      themeMode: isDark ? ThemeMode.dark : ThemeMode.light,
      //themeMode: ThemeMode.system,
      // // 从profile里获取个人定制的theme
      //themeMode: _usercontroller
      //     .themeStateFromProfileSettings,
      translations: LocalizationService(),
      //cong Profile里获取个人定制的locale
      locale: LocalizationService.localLocales[locale],
      fallbackLocale: LocalizationService.fallbackLocal,
      // locale: interfaceChinese
      //     ? LocalizationService.localChineseLocales[locale]
      //     : LocalizationService.localLocales[locale],
      // fallbackLocale: interfaceChinese
      //     ? LocalizationService.fallbackChineseLocal
      //     : LocalizationService.fallbackLocal,
      home: LoginReactive(),
      //TeacherHelp(),
      defaultTransition: Transition.fade,

      onGenerateRoute: RouteGenerator.generateRoute,
      builder: EasyLoading.init(),
    );
  }
}
